package mil.af.amc.adpetracker.web.actions.struts1.User;

import mil.af.amc.adpetracker.model.User;
import mil.af.amc.adpetracker.model.comparators.UserDisplaynameComparator;
import mil.af.amc.adpetracker.service.UserService;
import mil.af.amc.adpetracker.web.actions.struts1.AbstractAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Action to retrieve all users by a given organization
 *
 * @author TSgt Jason Ferguson
 */

public class GetUsersByOrganizationAction extends AbstractAction {

    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {

        int organizationId;
        try {
            organizationId = Integer.parseInt(httpServletRequest.getParameter("id"));
        } catch (NumberFormatException e) {
            return null;
        }

        if (organizationId < 0) {
            return null;
        }

        List<User> results = userService.getAllByOrganization(organizationId);
        Collections.sort(results, new UserDisplaynameComparator());
        
        JSONArray jsonArray = new JSONArray();
        for (User user : results) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", user.getId());
            map.put("name", user.getDisplayName());
            JSONObject jsonObject = JSONObject.fromObject(map);
            jsonArray.add(jsonObject);
        }

        httpServletResponse.setHeader("Content-Type", "application/json");
        httpServletResponse.getWriter().println(jsonArray);


        return null;

    }
}
